package demo;

import java.util.Arrays;

public class MyArrayList {
    public int[] elem;
    public int usedSize;
    public static final int DEFAULE_SIZE = 10;

    public MyArrayList(){
        this.elem = new int[DEFAULE_SIZE];
    }
    //打印顺序表
    public void display(){
        for (int i = 0; i < this.usedSize; i++) {
            System.out.print(this.elem[i]+ " ");
        }
        System.out.println();
    }
    //获取顺序表长度
    public int size(){
        return this.usedSize;
    }
    //判断是否包含某个元素
    public boolean contains(int tofind){
        for (int i = 0; i < this.usedSize; i++) {
            if(this.elem[i] == tofind){
                return true;
            }
        }
        return false;
    }
    //查找某个元素对应的位置
    public int indexOf(int toFind){
        for (int i = 0; i < this.usedSize; i++) {
            if(this.elem[i] == toFind){
                return i;
            }
        }
        return -1;
    }
    //新增元素，默认在数组最雄厚新增
    public void add(int data){
        if(this.isfull()){
            resize();
        }
        this.elem[this.usedSize] = data;
        this.usedSize++;
    }
    //扩容
    private void resize(){
        this.elem = Arrays.copyOf(this.elem,2*this.elem.length);
    }
    //判断是否满
    public boolean isfull(){
//        if(this.usedSize == this.elem.length){
//            return true;
//        }
        return this.usedSize == this.elem.length;
    }
    //在pos位置新增元素
    public void add(int pos , int data){
        checkIndex(pos);
        if(this.isfull()){
            resize();
        }
        for (int i = this.usedSize; i >= pos; i--) {
            this.elem[i+1] = this.elem[i];
        }
        this.elem[pos] = data;
        usedSize++;
    }
    //检查add的时候pos是否合法
    private void checkIndex(int pos){
        if(pos < 0 || pos > usedSize){
            throw new IndexOutOfException("位置不合法");
        }
    }
    public int get(int pos){
        checkGetIndex(pos);
        return this.elem[pos];
    }
    private void checkGetIndex(int pos){
        if(pos < 0 || pos >= usedSize){
            throw new IndexOutOfException("get元素的时候位置不合法");
        }
    }
    //给pos位置的元素设置为value
    public void set(int pos , int value){
        checkIndex(pos);
        this.elem[pos] = value;
    }
    //删除第一次出现的关键字key
    public boolean remove(int toRemove){
        int index = indexOf(toRemove);
        if(index == -1){
            System.out.println("没有这个数据 ");
            return false;
        }
        for (int i = index; i < usedSize -1 ; i++) {
            this.elem[i] = this.elem[i+1];
            this.elem[usedSize] = 0;
        }
        usedSize--;
        return true;
    }
    //清空顺序表
    public void clear(){
//        for (int i = 0; i < this.usedSize; i++) {
//            this.elem[i] = 0;
//        }
        this.usedSize = 0;
    }
}
